package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"newss/models"
)

type XinwenController struct {
	beego.Controller
}
type Msg struct {
	Code int
	Msg  string
	Data interface{}
}

func (c *XinwenController) Add() {
	biaoti := c.GetString("biaoti")
	fenlei := c.GetString("fenlei")
	ss := models.Newss{
		Biaoti: biaoti,
		Fenlei: fenlei,
	}
	err := models.DB.Debug().Create(&ss).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "添加失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "添加成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}

func (c *XinwenController) List() {
	var alloct []models.Newss
	err := models.DB.Debug().Find(&alloct).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "查找失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "查找成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *XinwenController) Update() {
	id, _ := c.GetInt("id")
	biaoti := c.GetString("biaoti")
	fenlei := c.GetString("fenlei")
	ss := models.Newss{
		Biaoti: biaoti,
		Fenlei: fenlei,
	}
	err := models.DB.Debug().Where("id=?", id).Updates(&ss).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "修改失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "修改成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *XinwenController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Debug().Delete(&models.Newss{}, id).Error
	if err != nil {
		res := Msg{
			Code: 0,
			Msg:  "删除失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := Msg{
			Code: 200,
			Msg:  "删除成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
